package com.service.impl;

import com.api.CodeService;
import com.api.MailService;
import com.entity.Code;
import com.repository.CodeRepository;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Date;
import java.util.Random;

@Service
@Transactional
public class CodeServiceImpl implements CodeService {
    private final static Integer EXPIRE = 10;
    private final static Integer CODE_LENGTH=6;
    @Resource
    private CodeRepository codeRepository;
    @Reference
    private MailService emailService;

    @Override
    public boolean create(String email){
        Code code = createCode(email);

        codeRepository.save(code);

        return  emailService.create(email,code.getCode());
    }


    private Code createCode(String email) {
        Code code = new Code();
        String vertifiCode = createCode(CODE_LENGTH);
        code.setCode(vertifiCode);
        Date date = new Date();
        Instant expireDate = date.toInstant().plusSeconds(EXPIRE*60);
        code.setCreateTime(date);
        code.setEmail(email);
        code.setExpireTime(Date.from(expireDate));
        return code;
    }

    @Override
    public boolean validate(String email, String code) {
        Code codeEntity =codeRepository.currentCodeByEmail(email);
        if(codeEntity!= null && codeEntity.getCode().equals(code) && codeEntity.getExpireTime().after(new Date())){
            return true;
        }
        return false;
    }

    Random random=new Random();
    private String createCode(int i){
        String code ="";
        for (int i1 = 0; i1 < i; i1++) {
            code += random.nextInt(9);
        }
        return code;
    }

}
